<?php
/**
 * Created by IntelliJ IDEA.
 * User: admin
 * Date: 4/8 0008
 * Time: 16:43
 */

namespace app\api\model;


use think\Model;

class Appbuyorder extends Model{

    /**
     * 生成预订单
     * @param $userid
     * @param $appid
     * @param $year
     * @param $price
     * @return bool
     */
    public function makepre($userid,$appid,$year,$price){
        $ordersn=strval(microtime(true)*10000);//生成预订单号
        $shopid=model("manager")->where("id",$userid)->column("shopid")[0];
        if(!$shopid){
            return false;
        }
        $oriinfo=\model("Userapp")->where("appid",$appid)->where(["shopid"=>$shopid])->find();
        if($oriinfo){
            $expiretime=strtotime("+".$year." year",time()>$oriinfo["endtime"]?time():$oriinfo["endtime"]);
            if(($expiretime>=pow(2,31)-1)||$expiretime<100){
                return false;
            }
            //        第一步:向Appbuyorder中记
            $this->data([
                "shopid"=>$shopid,
                "userid"=>$userid,
                "createtime"=>time(),
                "appid"=>$appid,
                "appname"=>\model("applist")->where("id",$appid)->find()["appname"],
                "expiretime"=>strtotime("+".$year." year",time()>$oriinfo["endtime"]?time():$oriinfo["endtime"]),
                "orderstatus"=>1,
                "price"=>$price,
                "num"=>$year,
                "sn"=>$ordersn,
                "buyway"=>"应用市场购买"
            ]);
            $res=$this->isUpdate(false)->save();
        }else{
            //        第一步:向Appbuyorder中记录
            $this->data([
                "shopid"=>$shopid,
                "userid"=>$userid,
                "createtime"=>time(),
                "appid"=>$appid,
                "appname"=>\model("applist")->where("id",$appid)->find()["appname"],
                "expiretime"=>strtotime("+".$year." year",time()),
                "orderstatus"=>1,
                "price"=>$price,
                "num"=>$year,
                "sn"=>$ordersn,
                "buyway"=>"应用市场购买"
            ]);
            $res=$this->save();
        }
        if($res){
            return $ordersn;//返回记录结果
        }else{
            return $res;//返回记录结果
        }
    }

}